<?php
// 前台基类
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2017 http://www.eacoo123.com, All rights reserved.
// +----------------------------------------------------------------------
// | [EacooPHP] 并不是自由软件,可免费使用,未经许可不能去掉EacooPHP相关版权。
// | 禁止在EacooPHP整体或任何部分基础上发展任何派生、修改或第三方版本用于重新分发
// +----------------------------------------------------------------------
// | Author:  心云间、凝听 <981248356@qq.com>
// +----------------------------------------------------------------------
namespace app\common\controller;

use app\common\controller\Base;
use think\Loader;
use think\facade\Config as thinkConfig;
use app\common\logic\User as UserLogic;

class WapBase extends Base {

	protected $isApp;
	protected $isWeixin;
	protected $weixinUserUpdateInterval;
	protected $cookieOpenidName;
	protected $cookieUnionidName;
	protected $cookieAccessTokenName;

	function initialize() {
		parent::initialize();

		$this->assign('suffix', '222');

		// 系统开关
		if (!$this->configInfo['toggle_web_site']) {
			$this->error('站点已经关闭，请稍后访问~');
		}

		//include UC_CLIENT_ROOT."config.inc.php";

		//判断微信还是app
		$isApp = strpos($_SERVER['HTTP_USER_AGENT'], "QianFan") !== false ? 1 : 0;
		$this->isApp = $isApp;
		$this->assign('isApp', $isApp);

		$isWeixin = strpos($_SERVER['HTTP_USER_AGENT'], "MicroMessenger") !== false ? 1 : 0;
		$this->isWeixin = $isWeixin;
		$this->assign('isWeixin', $isWeixin);

		//判断机型
		if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')){
			//echo 'systerm is IOS';
			$device = 'ios';
		}else if(strpos($_SERVER['HTTP_USER_AGENT'], 'Android')){
			//echo 'systerm is Android';
			$device = 'android';
		}else{
			//echo 'systerm is other';
			$device = 'other';
		}
		//$device = 'android';
		$this->assign('device', $device);

		//用户登陆相关
		$this->cookieOpenidName = 'mobmall_openid5';
		$this->cookieAccessTokenName = 'mobmall_accesstoken5';
		$this->weixinUserUpdateInterval = 60*5;
		
		// //系统配置增加文件缓存
		// $cacheData = cache('cache_config');
		// if (empty($cacheData)) {
		// 	$configModel = model('common/config');
		// 	list($cache_config) = $configModel->search(array('group'=>6), '');
		// 	//print_r($list);exit;

		// 	$options = [
		// 		 // 缓存类型为File
		// 		'type'   => 'File',
		// 		 // 缓存有效期为永久有效
		// 		'expire' => 0,
		// 		 // 指定缓存目录
		// 		'path'   => APP_PATH . 'runtime/cache/',
		// 	];
		// 	// 缓存初始化
		// 	cache($options);
		// 	// 设置缓存数据
		// 	cache('cache_config', $cache_config, 3600);
		// } else {
		// 	$cache_config = $cacheData;
		// 	//$this->assign('config_global', $configs);
		// }
		// thinkConfig::set($cache_config);// 添加配置


		//if (!$this->isWeixin) { //app
		//	$this->getPhpwind(); //获取phpwind论坛的用户信息
		//}
	}

	public function wapError($message, $jumpUrl='', $showLogin=0) {
		$this->assign("message", $message);
		$this->assign("jumpUrl", $jumpUrl);
		$this->assign("showLogin", $showLogin);
		echo $this->fetch(TPL_PATH."mobmall/wap_error.html");exit;
	}

	public function wapSuccess($message, $jumpUrl='') {
		$this->assign("message", $message);
		$this->assign("jumpUrl", $jumpUrl);
		$this->assign("waitSecond", 3);
		echo $this->fetch(TPL_PATH."mobmall/wap_success.html");exit;
	}

	function setSeoFrontNew($first_name) {
		if ($first_name) {
			$site_seo_title = $first_name.'_';
			$site_seo_keywords = $first_name.'_';
			$site_seo_description = $first_name.',';
		}

		$sys_identify = config('sys_identify');
		$f_config = cache($sys_identify);
		$sec_name = $f_config['sys_title'];

		if ($sec_name) {
			$site_seo_title .= $sec_name;
			$site_seo_keywords .= $sec_name;
			$site_seo_description .= $sec_name;
		}

// 		if ($site_options['site_seo_title']) {
// 			$site_seo_title .= $site_options['site_seo_title'];
// 			$site_seo_keywords .= $site_options['site_seo_keywords'];
// 			$site_seo_description .= $site_options['site_seo_description'];
// 		}

		$this->assign('site_seo_title', $site_seo_title);
		$this->assign('site_seo_keywords', $site_seo_keywords);
		$this->assign('site_seo_description', $site_seo_description);
	}

	function setSeoOrigin($first_name, $sec_name = '') {
		if ($first_name) {
			$site_seo_title = $first_name;
			$site_seo_keywords = $first_name;
			$site_seo_description = $first_name;
		}

		if ($sec_name) {
			$site_seo_title .= '_'.$sec_name;
			$site_seo_keywords .= '_'.$sec_name;
			$site_seo_description .= '_'.$sec_name;
		}

		$this->assign('site_seo_title', $site_seo_title);
		$this->assign('site_seo_keywords', $site_seo_keywords);
		$this->assign('site_seo_description', $site_seo_description);
	}

	public function setWeixinAndGetUser() {
		$nowTime = $this->ts;

		if ($this->isWeixin) { //微信
			//获取微信公众号信息
			$wechatAccountDao = model('manage/WechatAccount');
			$wxdb = $wechatAccountDao->getInfo(config('authorize_wid'));

			//微信jssdk
			$jssdk = new \org\weixin\jssdk($wxdb['appid'], $wxdb['appsecret'], $wxdb['weixin']);
			$signPackage = $jssdk->getSignPackage();
			$this->assign('signPackage', $signPackage);
			//微信jssdk end

			//获取缓存中的access_token
			$access_token = $jssdk->getAccessTokenForOut();

			$options = array(
				'token'=>$wxdb['token'], //填写你设定的key
				'encodingaeskey'=>$wxdb['aeskey'], //填写加密用的EncodingAESKey
				'appid'=>$wxdb['appid'], //填写高级调用功能的app id, 请在微信开发模式后台查询
				'appsecret'=>$wxdb['appsecret'], //填写高级调用功能的密钥
				'partnerid'=>'', //财付通商户身份标识，支付权限专用，没有可不填
				'partnerkey'=>'', //财付通商户权限密钥Key，支付权限专用
				'paysignkey'=>'' //商户签名密钥Key，支付权限专用
			);
			$weObj = new \wechat\Wechat($options);

			//使用jssdk获取到的access_token赋值，下文要用
			$weObj->checkAuth('', '', $access_token);
			//echo 1;exit;
			
			$openid = cookie($this->cookieOpenidName);
			//$unionid = cookie($this->cookieUnionidName);
			$user_access_token = cookie($this->cookieAccessTokenName);

/*
array(
	'access_token' => '6_pbIAURDeW_jh5JutHQsHx-0UYM6jc3XwmaPJtCjjN4nbcSmXlFZ7Kh8raVma-avwYDXbw002LagBpgxu-TwFFpWXSQ3ZkmEPljITB_amFSc',
	'expires_in' => '7200',
	'refresh_token' => '6_QE0i_E6CZAYzxEecKK23pOY_wH0U6JAP-iZWBlNVgjYyXRwgyqHqBLdlDoLGT6emMZIe0Pr7RClb6ZfDaeEKSonqJZ0xAoEPRD02ADGpVaA',
	'openid' => 'oXz-Vwe3I9mv4lNP9x8otEmCBpYE',
	'scope' => 'snsapi_userinfo',
	'unionid' => 'oFfS0wgODYhHTjcWXOlFmz5vBX5g',
)
*/
			if (empty($openid) || empty($user_access_token)) {
				//获取openid、access_token
				$json = $weObj->getOauthAccessToken();
				db('Aaaa')->insert(array('flag'=>'mobmall-json', 'content'=>pw_var_export($json)));
				$openid = $json['openid'];
				//$unionid = $json['unionid'];
				$user_access_token = $json['access_token'];
				$expires_in = $json['expires_in'];
				$expires_in = '1800'; //7200秒，2小时，但是我改短一点。

				if (empty($openid)) { //通过微信接口获取不到openid，则继续获取
					$callback = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
					//echo $callback;exit;
					$url = $weObj->getOauthRedirect($callback, 1); //请求微信接口，通过oauth2认证获得来访用户的code值
					header("Location:".$url);exit;
				} else {
					cookie($this->cookieOpenidName, $openid, $expires_in);
					//cookie($this->cookieUnionidName, $unionid, $expires_in);
					cookie($this->cookieAccessTokenName, $user_access_token, $expires_in);
				}
			}

			//$userInfo = $this->userDao->getInfoByUnionid($unionid); //根据unionid获取用户信息
			$userInfo = $this->userDao->getInfoByOpenid($openid); //根据openid获取用户信息
			//print_r($userInfo);exit;

			if (!$userInfo) { //=====用户不存在
				$wxUserInfo = $weObj->getOauthUserinfo($user_access_token, $openid);
				if ($wxUserInfo === false) {
					$this->reportOauthUserinfo($weObj);
				}

				$data = array(
					'openid'			=> $openid,
					'unionid'			=> (string) $wxUserInfo['unionid'],
					'username'			=> $wxUserInfo['nickname'],
					'avatar'			=> $wxUserInfo['headimgurl'],
					'gender'			=> $wxUserInfo['sex'],
					'city'				=> $wxUserInfo['city'],
					'last_login_time'	=> $nowTime,
				);
				$data['create_time'] = $nowTime;

				//验证用户是否关注
				// if (1) {
				// 	$wxUserInfo2 = $weObj->getUserInfo($openid); //获取关注者详细信息
				// 	if ($wxUserInfo2 !== false) {
				// 		$data['subscribe'] = $wxUserInfo2['subscribe'];
				// 	}
				// }

				$id = $this->userDao->baseAddData($data); //插入用户数据
				$moondb = $data;
				$moondb['from'] = 'wx-add';
				$moondb['id'] = $id;
				$moondb['source'] = 'wx';
			} else if ($nowTime - $userInfo['last_time'] > $this->weixinUserUpdateInterval) { //=====更新用户数据
				$wxUserInfo = $weObj->getOauthUserinfo($user_access_token, $openid);
				if ($wxUserInfo === false) {
					$this->reportOauthUserinfo($weObj);
				}

				$data = array(
					'openid'			=> $openid,
					'unionid'			=> (string) $wxUserInfo['unionid'],
					'username'			=> $wxUserInfo['nickname'],
					'avatar'			=> $wxUserInfo['headimgurl'],
					'gender'			=> $wxUserInfo['sex'],
					'city'				=> $wxUserInfo['city'],
					'last_login_time'	=> $nowTime,
				);

				//验证用户是否关注
				// if (1) {
				// 	$wxUserInfo2 = $weObj->getUserInfo($openid); //获取关注者详细信息
				// 	if ($wxUserInfo2 !== false) {
				// 		$data['subscribe'] = $wxUserInfo2['subscribe'];
				// 	}
				// }

				$this->userDao->baseUpdateData($userInfo['id'], $data);
				$moondb = $data;
				$moondb['from'] = 'wx-update';
				$moondb['id'] = $userInfo['id'];
				$moondb['source'] = 'wx';
			} else {
				$moondb = $userInfo;
				$moondb['from'] = 'wx-other';
				$moondb['source'] = 'wx';

				//用户没有关注的情况
				// if (1 && $moondb['subscribe'] == 0) {
				// 	$wxUserInfo2 = $weObj->getUserInfo($openid); //获取关注者详细信息
				// 	if ($wxUserInfo2 !== false) {
				// 		$data = [
				// 			'subscribe'		=> $wxUserInfo2['subscribe']
				// 		];
				// 		$this->userDao->save($data, ['id'=>$userInfo['id']]);
				// 		$moondb['subscribe'] = $wxUserInfo2['subscribe'];
				// 	}
				// }
			}
		} else { //app及其他
			$moonuid = UserLogic::isLogin();
			
			if ($moonuid) { //=====用户不存在
				//获取用户信息
				$userDao = model('common/User');
				$moondb = $userDao->getInfo($moonuid);
				$moondb['source'] = 'pc';
			} else {
				$moondb = array(
					'source'	=> 'pc-none',
					'from'		=> 'app-none',
					'id'		=> 0,
					'pwuid'		=> 0,
					'username'	=> '游客',
					'avatar'	=> '/themes/public/images/avatar/none.gif',
					'mobile'	=> '',
				);
			}
		}

		$moondb['uid'] = $moondb['id'];
		$this->moonuid = $moondb['id'];
		$this->moonname = $moondb['username'];
		$this->moonavatar = $moondb['avatar'];
		$this->moondb = $moondb;
		$this->assign('moondb', $moondb);

		//查询当前购物车数量
		$orderProductDao = model('mobmall_manage/OrderProduct');
		$cartNum = $orderProductDao->countSearch(['uid'=>$this->moonuid]);
		$this->assign('cartNum', $cartNum);
	}

	public function reportOauthUserinfo($weObj) {
		db('Aaaa')->insert(['space'=>'reportOauthUserinfo', 'flag'=>'wxUserInfo', 'content'=>'用户授权信息非法。errCode：'.$weObj->errCode.';errMsg：'.$weObj->errMsg]);
		
		//提示授权非法的话，就是access_token失效了，所以清空掉，并重新获取
		cookie($this->cookieOpenidName, null);
		cookie($this->cookieUnionidName, null);
		cookie($this->cookieAccessTokenName, null);
		$this->wapError('用户授权信息非法，请重新打开页面');
	}
	
	public function checkIsLoginAjax() {
		if (!$this->moonuid) {
			if ($this->isWeixin) {
				$this->error('微信授权用户信息非法，可能哪里出了问题。来源：'.$this->moondb['from']);
			} else {
				$this->error('请先登陆再继续操作<br><a href="'.url('wap/login/index').'" style="color:red">立即登录</a>');
			}
		}
	}

	public function checkIsLoginWap() {
		if (!$this->moonuid) {
			if ($this->isWeixin) {
				$this->wapError('微信授权用户信息非法，可能哪里出了问题。来源：'.$this->moondb['from']);
			} else {
				$this->wapError('请先登陆再继续操作<br><a href="'.url('wap/login/index').'" style="color:red">立即登录</a>');
			}
		}
	}

}